import { H3Event } from 'h3'
import { verify } from 'jsonwebtoken'

const TOKEN_TYPE = 'Bearer'

const extractToken = (authHeaderValue: string) => {
  const [, token] = authHeaderValue.split(`${TOKEN_TYPE} `)
  return token
}

export default eventHandler((event: H3Event) => {
  const authHeaderValue = getRequestHeader(event, 'authorization')
  const extractedToken = authHeaderValue ? extractToken(authHeaderValue) : getCookie(event, 'auth:token')!
  try {
    event.context.user = verify(extractedToken, useRuntimeConfig().secret)
  } catch (error) {
    // console.error('Login failed. Here\'s the raw error:', error)
    // throw createError({ statusCode: 403, statusMessage: 'You must be logged in to use this endpoint' })
  }
})
